//
//  DAImageView.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/27.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAImageView.h"
#import "Utility.h"
#import <AVFoundation/AVFoundation.h>
#define kUpdateInterval 0.02f
#define kRotateRadius 0.1f
#define pushPinWidth 20.0f
@interface DAImageView()<PushPinViewDelegate>{
    CGPoint oldCenter;
    CGRect imageFrame;
    UIView *superView;
}

@end

@implementation DAImageView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.userInteractionEnabled = YES;
        //抗锯齿
        self.layer.shouldRasterize = YES;
        [self.layer setRasterizationScale:2];
        [self.layer setBorderWidth:5];
        [self.layer setBorderColor:[UIColor whiteColor].CGColor];
        self.clipsToBounds = YES;
        [self setAnchorPoint:CGPointMake(0.5, 0)];
        oldCenter = self.center;
        UIPanGestureRecognizer *pan =[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handleDragGesture:)];
        [self addGestureRecognizer:pan];
        imageFrame = frame;
        [self configureViewMotion:frame];
    }
    return self;
}

- (void)showOnView:(UIView *)sView{
    superView = sView;
    [superView addSubview:self];
    [self configurePushPin];
}
//配置按钉
- (void)configurePushPin{
    _pushPin = [[PushPinView alloc]initWithPoint:CGPointMake(oldCenter.x, oldCenter.y) superView:superView];
    _pushPin.delegate = self;
    _pushPin.viscosity  = 20;
    _pushPin.bubbleWidth = pushPinWidth;
    _pushPin.bubbleColor = [UIColor whiteColor];
    [_pushPin setUp];
}
//配置背景页面
- (void)configureBackView{
    self.backView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.backView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [self.superview insertSubview:self.backView belowSubview:self];
    UITapGestureRecognizer *tapBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickBackView:)];
    [self.backView addGestureRecognizer:tapBackView];
    self.backView.userInteractionEnabled = YES;
}

#pragma mark - 手势方法
- (void)clickBackView:(UITapGestureRecognizer *)tap{
    [self.delegate viewWillReturn];
    //[self viewReturn];
}
//view复原
- (void)viewReturn{
    [self.backView removeFromSuperview];
    [self configureViewMotion:imageFrame];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(handleDragGesture:)];
    [self addGestureRecognizer:pan];
    self.transform = CGAffineTransformMakeScale(1.0,1.0);
    self.frame = imageFrame;
    [self configurePushPin];
}

//拖拽方法
- (void)handleDragGesture:(UIPanGestureRecognizer *)drag{
    if(drag.state == UIGestureRecognizerStateBegan){
        [_motionManager stopDeviceMotionUpdates];
        double rotation = atan(0);
        self.transform = CGAffineTransformMakeRotation(rotation);
        CGPoint anchorPoint = [drag locationInView:self];
        [self setAnchorPoint:CGPointMake(anchorPoint.x/self.frame.size.width, anchorPoint.y/self.frame.size.height)];
    }
    if (drag.state == UIGestureRecognizerStateChanged) {
        CGPoint dragPoint = [drag locationInView:self.superview];
        self.center = dragPoint;
        }
    if (drag.state == UIGestureRecognizerStateEnded ||
        drag.state == UIGestureRecognizerStateCancelled ||
        drag.state == UIGestureRecognizerStateFailed) {
        [self setAnchorPoint:CGPointMake(0.5, 0)];
        CGFloat centerDistance = sqrtf((self.center.x - oldCenter.x) * (self.center.x - oldCenter.x) + (self.center.y - oldCenter.y) * (self.center.y - oldCenter.y));
        if(centerDistance < 80){
            [self configureViewMotion:imageFrame];
            [UIView animateWithDuration:0.5
                                  delay:0.0f
                 usingSpringWithDamping:0.4f
                  initialSpringVelocity:0.0f
                                options:UIViewAnimationOptionCurveEaseInOut
                             animations:^{
                                 self.center = oldCenter;
                             }
                             completion:^(BOOL finished) {
                             }];
        }
    }
    [_pushPin dragImageView:drag];
}

#pragma mark - PushPinViewDelegate
- (void)viewDragFinished:(UIPanGestureRecognizer *)ges{
    [self configureBackView];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:0.4 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, 5);
        self.transform = CGAffineTransformMakeScale(1.3,1.3);
    } completion:^(BOOL finished) {
        [self removeGestureRecognizer:ges];
        [self.delegate viewDragFinished];
    }];
}

- (void)setGravityEnabled:(BOOL)gravityEnabled{
    if(!gravityEnabled){
        [self setAnchorPoint:CGPointMake(0.5, 0.5)];
        [_motionManager stopDeviceMotionUpdates];
    }
}
- (void)dealloc{
    [_motionManager stopDeviceMotionUpdates];
    _motionManager = nil;
}
//配置陀螺仪
- (void)configureViewMotion:(CGRect)frame{
    _motionManager = [[CMMotionManager alloc]init];
    if([_motionManager isDeviceMotionAvailable]){
        if (![_motionManager  isDeviceMotionActive]){
            DAImageView * __weak weakSelf = self;
            if (_motionManager.deviceMotionAvailable) {
                _motionManager.deviceMotionUpdateInterval = kUpdateInterval;
                [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *data, NSError *error) {
                    if(data.gravity.x > -kRotateRadius && data.gravity.x < kRotateRadius){
                        double rotation = atan(data.gravity.x);
                        weakSelf.transform = CGAffineTransformMakeRotation(-rotation);
                       // NSLog(@"!!!!");
                    }
                }];
            }
        }
    }else {
    }
}
//修改中心点并修复位移
- (void)setAnchorPoint:(CGPoint)anchorPoint
{
    CGPoint oldOrigin = self.frame.origin;
    self.layer.anchorPoint = anchorPoint;
    CGPoint newOrigin = self.frame.origin;
    
    CGPoint transition;
    transition.x = newOrigin.x - oldOrigin.x;
    transition.y = newOrigin.y - oldOrigin.y;
    
    self.center = CGPointMake (self.center.x - transition.x, self.center.y - transition.y);
}
@end

@implementation PushPinView {
    UIBezierPath *cutePath;
    UIColor *fillColorForCute;
    UIDynamicAnimator *animator;
    UISnapBehavior *snap;
    
    UIView *backView;
    CGFloat r1;
    CGFloat r2;
    CGFloat x1;
    CGFloat y1;
    CGFloat x2;
    CGFloat y2;
    CGFloat centerDistance;
    CGFloat cosDigree;
    CGFloat sinDigree;
    
    CGPoint pointA; // A
    CGPoint pointB; // B
    CGPoint pointD; // D
    CGPoint pointC; // C
    CGPoint pointO; // O
    CGPoint pointP; // P
    
    CGRect oldBackViewFrame;
    CGPoint initialPoint;
    CGPoint oldBackViewCenter;
    CAShapeLayer *shapeLayer;
    CGPoint oldDragPoint;
    
    BOOL isSound;
}

- (id)initWithPoint:(CGPoint)point superView:(UIView *)view {
    self = [super initWithFrame:CGRectMake(point.x, point.y , self.bubbleWidth,self.bubbleWidth)];
    if (self) {
        initialPoint = point;
        self.containerView = view;
        [self.containerView addSubview:self];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)displayLinkAction {
    x1 = backView.center.x;
    y1 = backView.center.y;
    x2 = self.frontView.center.x;
    y2 = self.frontView.center.y;
    
    centerDistance = sqrtf((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
    if (centerDistance == 0) {
        cosDigree = 1;
        sinDigree = 0;
    } else {
        cosDigree = (y2 - y1) / centerDistance;
        sinDigree = (x2 - x1) / centerDistance;
    }
    
    r1 = oldBackViewFrame.size.width / 2 - centerDistance / self.viscosity;
    
    pointA = CGPointMake(x1 - r1 * cosDigree, y1 + r1 * sinDigree); // A
    pointB = CGPointMake(x1 + r1 * cosDigree, y1 - r1 * sinDigree); // B
    pointD = CGPointMake(x2 - r2 * cosDigree, y2 + r2 * sinDigree); // D
    pointC = CGPointMake(x2 + r2 * cosDigree, y2 - r2 * sinDigree); // C
    pointO = CGPointMake(pointA.x + (centerDistance / 2) * sinDigree,
                         pointA.y + (centerDistance / 2) * cosDigree);
    pointP = CGPointMake(pointB.x + (centerDistance / 2) * sinDigree,
                         pointB.y + (centerDistance / 2) * cosDigree);
    
    [self drawRect];
}

- (void)drawRect {
    backView.center = oldBackViewCenter;
    backView.bounds = CGRectMake(0, 0, r1 * 2, r1 * 2);
    backView.layer.cornerRadius = r1;
    
    cutePath = [UIBezierPath bezierPath];
    [cutePath moveToPoint:pointA];
    [cutePath addQuadCurveToPoint:pointD controlPoint:pointO];
    [cutePath addLineToPoint:pointC];
    [cutePath addQuadCurveToPoint:pointB controlPoint:pointP];
    [cutePath moveToPoint:pointA];
    
    if (backView.hidden == NO) {
        shapeLayer.path = [cutePath CGPath];
        shapeLayer.fillColor = [fillColorForCute CGColor];
        [self.containerView.layer insertSublayer:shapeLayer
                                           below:self.frontView.layer];
    }
    
}

- (void)setUp {
    shapeLayer = [CAShapeLayer layer];
    self.backgroundColor = [UIColor clearColor];
    self.frontView = [[UIView alloc]
                      initWithFrame:CGRectMake(initialPoint.x - self.bubbleWidth/2, initialPoint.y - self.bubbleWidth/2, self.bubbleWidth,
                                               self.bubbleWidth)];
    
    r2 = self.frontView.bounds.size.width / 2;
    self.frontView.layer.cornerRadius = r2;
    self.frontView.backgroundColor = self.bubbleColor;
    
    backView = [[UIView alloc] initWithFrame:self.frontView.frame];
    r1 = backView.bounds.size.width / 2;
    backView.layer.cornerRadius = r1;
    backView.backgroundColor = self.bubbleColor;
    
    [self.containerView addSubview:backView];
    [self.containerView addSubview:self.frontView];

    x1 = backView.center.x;
    y1 = backView.center.y;
    x2 = self.frontView.center.x;
    y2 = self.frontView.center.y;
    
    pointA = CGPointMake(x1 - r1, y1); // A
    pointB = CGPointMake(x1 + r1, y1); // B
    pointD = CGPointMake(x2 - r2, y2); // D
    pointC = CGPointMake(x2 + r2, y2); // C
    pointO = CGPointMake(x1 - r1, y1); // O
    pointP = CGPointMake(x2 + r2, y2); // P
    
    oldBackViewFrame = backView.frame;
    oldBackViewCenter = backView.center;

    UIView *pointView = [[UIView alloc]initWithFrame:CGRectMake(3, 3, self.frontView.frame.size.width - 6, self.frontView.frame.size.height - 6)];
    [pointView.layer setCornerRadius:self.frontView.frame.size.width/2 -3];
    pointView.clipsToBounds = YES;
    pointView.backgroundColor = [UIColor lightGrayColor];
    [self.frontView addSubview:pointView];
}

- (void)dragImageView:(UIPanGestureRecognizer *)ges{
    [self handleDragGesture:ges];
}

- (void)handleDragGesture:(UIPanGestureRecognizer *)ges {
    CGPoint dragPoint = [ges locationInView:self.containerView];
    if (ges.state == UIGestureRecognizerStateBegan) {
        isSound = YES;
        backView.hidden = NO;
        oldDragPoint = dragPoint;
        fillColorForCute = self.bubbleColor;
        [self RemoveAniamtionLikeGameCenterBubble];
    } else if (ges.state == UIGestureRecognizerStateChanged){
        CGFloat dragX = dragPoint.x - oldDragPoint.x ;
        CGFloat dragY = dragPoint.y - oldDragPoint.y ;
        self.frontView.center = CGPointMake(initialPoint.x + dragX, initialPoint.y + dragY);
        if (r1 <= 6) {
            fillColorForCute = [UIColor clearColor];
            backView.hidden = YES;
            [shapeLayer removeFromSuperlayer];
            if(isSound){
                NSURL *url = [[NSBundle mainBundle] URLForResource:@"594.mp3" withExtension:nil];
                SystemSoundID soundID = 0;
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
                AudioServicesPlaySystemSound(soundID);
                isSound = NO;
            }
        }
        [self displayLinkAction];
    } else if (ges.state == UIGestureRecognizerStateEnded ||
               ges.state == UIGestureRecognizerStateCancelled ||
               ges.state == UIGestureRecognizerStateFailed) {
        
        if (r1 <= 6) {
            [self.frontView setHidden:YES];
            [self.delegate viewDragFinished:ges];
        } else {
            backView.hidden = YES;
            fillColorForCute = [UIColor clearColor];
            [shapeLayer removeFromSuperlayer];
            [UIView animateWithDuration:0.5
                                  delay:0.0f
                 usingSpringWithDamping:0.4f
                  initialSpringVelocity:0.0f
                                options:UIViewAnimationOptionCurveEaseInOut
                             animations:^{
                                 self.frontView.center = oldBackViewCenter;
                             }
                             completion:^(BOOL finished) {
                             }];
        }
    }
}

- (void)RemoveAniamtionLikeGameCenterBubble {
    [self.frontView.layer removeAllAnimations];
}

@end
